/**
 * 重复输出字符串
 * @param str
 * @param num
 * @returns {string}
 */

// 1.
function repeat(str, num) {
    // 请把你的代码写在这里
    var repeatedString = "";
    for(var i = 0; i < num ;i++) {
        repeatedString += str;
    }
    return repeatedString;
}

repeat("abc", 3);
console.log(repeat("abc", -3));

// 2. 通过条件判断和递归重复输出一个字符串
function repeatStringNumTimes(string, times) {
    // 步骤1.检查 times 是否为负数，如果为 true 则返回一个空字符串
    if (times < 0) {
        return "";
    }

    // 步骤2.检查times是否等于1，如果是，返回字符串本身。
    if (times === 1) {
        return string;
    }

    // 步骤3. 使用递归
    else {
        return string + repeatStringNumTimes(string, times - 1); // return "abcabcabc";
    }
    /*
      递归方法的第一部分你需要记住，你不会只调用一次，您将有好几个嵌套调用
                   times       string + repeatStringNumTimes(string, times - 1)
        1st call   3           "abc" + ("abc", 3 - 1)
        2nd call   2           "abc" + ("abc", 2 - 1)
        3rd call   1           "abc" => if (times === 1) return string;
        4th call   0           ""   => if (times <= 0) return "";
      递归方法的第二部分
        4th call will return      ""
        3rd call will return     "abc"
        2nd call will return     "abc"
        1st call will return     "abc"
      最后调用是串联所有字符串
      return "abc" + "abc" + "abc"; // return "abcabcabc";
    */
}
repeatStringNumTimes("abc", 3);

// 3 ES6 `repeat()`
function repeatStringNumTimes2(string, times) {
    //步骤1.如果 times 为正数，返回重复的字符串
    if (times > 0) { // (3 > 0) => true
        return string.repeat(times); // return "abc".repeat(3); => return "abcabcabc";
    }

    //Step 2. Else 如果times是负数，如果为true则返回一个空字符串
    else {
        return "";
    }
}

console.log(repeatStringNumTimes2("abc", 3));
repeatStringNumTimes2("abc", 3);

// 4 三元表达式
function repeatStringNumTimes3(string, times) {
    return times > 0 ? string.repeat(times) : "";
}
repeatStringNumTimes3("abc", 3);